package com.woniuxy.classdeans.utils;

import javax.websocket.RemoteEndpoint.Basic;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketUtil {
	//存放所有在聊天室里面的客户端对应的session
	////ConcurrentHashMap  线程安全的hashmap
	public  static final Map<String, Session> User=new ConcurrentHashMap<String, Session>();
	


	//发送给某指定对象
	public static void sendToTokenMessage(String token,String message){
		//如果未传入值直接返回
		if(token==null) return;

		Session session = User.get(token);
		//如果存在远程连接就发送给年级主任
		if (session!=null&&session.getBasicRemote()!=null){
			//获取远程连接
			Basic basicRemote = session.getBasicRemote();
			try {

				basicRemote.sendText(message);//发送消息

			} catch (IOException e) {

				e.printStackTrace();
			}


		}
	}

	//发送消息
	public static void sendMessage(Session session,String message) {
//		获取发送数据的远程对象
		Basic basicRemote = session.getBasicRemote();
		//连接有效
		if(basicRemote!=null) {
			try {
				basicRemote.sendText(message);//发送消息
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	//发给所有人 
	public static void sendAll(String message) {
		//迭代器遍历
		 Iterator<String> iterator = User.keySet().iterator();
		
		if(iterator.hasNext()) {
			String key = iterator.next();
			Session session = User.get(key);
			//发送消息 
			sendMessage(session,message);
		}
		
	}
	
	
}
